package leetcode.p451;

import java.util.*;

/**
 * @author: trtan
 * @date: 2021-07-03 08:03
 **/
public class SortCharactersByFrequency {
    /**
     * 计数 排序
     * @param s
     * @return java.lang.String
     * @author trtan
     * @date 2021/7/3 8:10
     */
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            int count = map.getOrDefault(s.charAt(i), 0) + 1;
            map.put(s.charAt(i), count);
        }
        List<Character> list = new ArrayList<>(map.keySet());
        Collections.sort(list, (a, b) -> map.get(b) - map.get(a));
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            Character key = list.get(i);
            int value = map.get(key);
            for (int j = 0; j < value; j++) {
                result.append(key);
            }
        }
        return result.toString();
    }
}
